#!/usr/bin/env bash

# 核心服务启动脚本
# 兼容macOS zsh环境

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# JVM参数配置
GATEWAY_JVM_ARGS="-Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=256m -XX:+UseG1GC"
SYSTEM_JVM_ARGS="-Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=256m -XX:+UseG1GC"
AUTH_JVM_ARGS="-Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=256m -XX:+UseG1GC"

# 服务列表 (核心服务)
declare -A CORE_SERVICES=(
    ["gateway"]="zx-services/zx-gateway-15775"
    ["system"]="zx-services/zx-system-block-15776"
    ["auth"]="zx-services/zx-auth-15778"
)

# 显示帮助信息
show_help() {
    echo -e "${BLUE}核心服务启动脚本${NC}"
    echo "使用方法: ./start-core-services.sh [选项]"
    echo ""
    echo "选项:"
    echo "  help           显示帮助信息"
    echo "  stop           停止所有核心服务"
    echo ""
    echo "示例:"
    echo "  ./start-core-services.sh      # 启动所有核心服务"
    echo "  ./start-core-services.sh stop # 停止所有核心服务"
}

# 启动单个服务
start_service() {
    local service_name=$1
    local service_path=${CORE_SERVICES[$service_name]}
    
    if [ -z "$service_path" ]; then
        echo -e "${RED}错误: 未知服务 $service_name${NC}"
        return 1
    fi
    
    echo -e "${YELLOW}正在启动服务: $service_name${NC}"
    
    # 设置JVM参数
    local jvm_args=""
    case "$service_name" in
        "gateway")
            jvm_args="$GATEWAY_JVM_ARGS"
            ;;
        "system")
            jvm_args="$SYSTEM_JVM_ARGS"
            ;;
        "auth")
            jvm_args="$AUTH_JVM_ARGS"
            ;;
    esac
    
    # 在后台启动服务
    cd "$service_path" || return 1
    command mvn spring-boot:run -Djvm.args="$jvm_args" &
    cd - > /dev/null || return 1
    
    echo -e "${GREEN}服务 $service_name 已在后台启动${NC}"
}

# 停止所有服务
stop_services() {
    echo -e "${YELLOW}正在停止所有核心服务...${NC}"
    command pkill -f "spring-boot:run"
    echo -e "${GREEN}所有核心服务已停止${NC}"
}

# 启动所有核心服务
start_all_core_services() {
    echo -e "${YELLOW}启动所有核心服务...${NC}"
    # 按正确顺序启动服务，确保依赖关系
    start_service "gateway"
    sleep 3  # 等待网关服务启动
    start_service "system"
    sleep 3  # 等待系统服务启动，因为认证服务需要调用它
    start_service "auth"
    echo -e "${GREEN}所有核心服务启动完成${NC}"
}

# 主逻辑
main() {
    # 检查参数
    if [ $# -eq 0 ]; then
        start_all_core_services
        exit 0
    fi
    
    # 处理选项
    case "$1" in
        help)
            show_help
            exit 0
            ;;
        stop)
            stop_services
            exit 0
            ;;
        *)
            echo -e "${RED}错误: 未知选项 $1${NC}"
            show_help
            exit 1
            ;;
    esac
}

# 执行主逻辑
main "$@"